package com.haohan.jingyuan.customer.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.config.properties.ShareProperties;
import com.haohan.jingyuan.customer.dao.CustomerFileMapper;
import com.haohan.jingyuan.customer.dao.CustomerFileShareMapper;
import com.haohan.jingyuan.customer.dao.CustomerGroupMapper;
import com.haohan.jingyuan.customer.entity.CustomerGroupInfo;
import com.haohan.jingyuan.customer.dto.req.CreateFileShareRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteFileShareRequest;
import com.haohan.jingyuan.customer.dto.req.QueryFileShareListRequest;
import com.haohan.jingyuan.customer.dto.req.UpdateFileShareRequest;
import com.haohan.jingyuan.customer.dto.resp.FileShareInfoResp;
import com.haohan.jingyuan.customer.dto.resp.FileShareListResp;
import com.haohan.jingyuan.customer.entity.CustomerFile;
import com.haohan.jingyuan.customer.entity.CustomerFileShare;
import com.haohan.jingyuan.customer.helper.FileShareRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import com.haohan.jingyuan.util.OssUtil;
import com.haohan.jingyuan.util.QrCodeToolUtil;
import com.haohan.jingyuan.util.UuidUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 客户材料分享服务实现类
 *
 * @ClassName CustomerFileShareService
 * @Description 客户材料分享相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/11/04 17:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerFileShareService {

    /**
     * 客户材料分享Mapper
     */
    private final CustomerFileShareMapper customerFileShareMapper;

    /**
     * 客户材料Mapper
     */
    private final CustomerFileMapper customerFileMapper;

    /**
     * 客户分组Mapper
     */
    private final CustomerGroupMapper customerGroupMapper;

    /**
     * OSS工具类
     */
    private final OssUtil ossUtil;

    /**
     * 分享配置属性
     */
    private final ShareProperties shareProperties;

    /**
     * 创建文件分享
     *
     * @param request 创建文件分享请求
     * @return 文件分享信息
     */
    public FileShareInfoResp createFileShare(CreateFileShareRequest request) {
        // 根据fileKey查询CustomerFile
        CustomerFile customerFile = customerFileMapper.findByFileKey(request.getFileKey());
        if (customerFile == null) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "文件不存在");
        }

        // 获取customerId和groupCode
        String customerId = customerFile.getCustomerId();
        String groupCode = customerFile.getGroupCode();

        // 使用UuidUtil.generateId("SHARE_", 10)生成shareId
        String shareId = UuidUtil.generateId("SHARE_", 10);
        String visitCode = UuidUtil.generateId(8);

        // 拼接完整的分享链接：前缀 + shareId
        Map<String, String> placeholderValues = new HashMap<>();
        placeholderValues.put("share_id", shareId);
        placeholderValues.put("visit_code", visitCode);
        String shareUrl = StrUtil.format(shareProperties.getPrefix(), placeholderValues);

        // 生成二维码图片
        InputStream qrCodeInputStream = QrCodeToolUtil.generateQrCode(shareUrl);

        // 上传二维码图片到OSS，获取ossKey
        String qrCodeOssKey = ossUtil.uploadFile(qrCodeInputStream, "qr_" + shareId + ".png", "image/png");
        String qrTmpUrl = ossUtil.getFileUrl(qrCodeOssKey);

        // 创建分享记录
        CustomerFileShare customerFileShare = new CustomerFileShare();
        customerFileShare.setShareId(shareId);
        customerFileShare.setVisitCode(visitCode);
        customerFileShare.setFileKey(request.getFileKey());
        customerFileShare.setCustomerId(customerId);
        customerFileShare.setGroupCode(groupCode);
        customerFileShare.setQrCodeOssKey(qrCodeOssKey);
        customerFileShare.setExpireAt(request.getExpireAt());
        EntityUtil.setCreateAndModifyInfo(customerFileShare, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        int result = customerFileShareMapper.insert(customerFileShare);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        // 查询分组信息
        Map<String, CustomerGroupInfo> groupMap = null;
        if (customerFileShare.getGroupCode() != null && !customerFileShare.getGroupCode().trim().isEmpty()) {
            CustomerGroupInfo group = customerGroupMapper.findByGroupIdAndType(customerFileShare.getGroupCode(), 2);
            if (group != null) {
                groupMap = new HashMap<>();
                groupMap.put(group.getGroupId(), group);
            }
        }

        // 查询文件信息（customerFile已在方法开始处查询）
        Map<String, CustomerFile> fileMap = null;
        if (customerFile != null) {
            fileMap = new HashMap<>();
            fileMap.put(customerFile.getFileKey(), customerFile);
        }

        FileShareInfoResp resp = FileShareRespHelper.convert2FileShareInfoResp(customerFileShare, groupMap, fileMap);
        resp.setQrTmpUrl(qrTmpUrl);
        return resp;
    }

    /**
     * 更新文件分享
     *
     * @param request 更新文件分享请求
     * @return 文件分享信息
     */
    public FileShareInfoResp updateFileShare(UpdateFileShareRequest request) {
        // 查询分享记录是否存在
        Long id = Long.parseLong(request.getId());
        CustomerFileShare customerFileShare = customerFileShareMapper.selectById(id);
        if (customerFileShare == null) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "分享记录不存在");
        }

        // 更新分享记录信息
        if (request.getExpireAt() != null) {
            customerFileShare.setExpireAt(request.getExpireAt());
        }
        EntityUtil.setModifyInfo(customerFileShare, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerFileShareMapper.updateById(customerFileShare);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        // 查询分组信息
        Map<String, CustomerGroupInfo> groupMap = null;
        if (customerFileShare.getGroupCode() != null && !customerFileShare.getGroupCode().trim().isEmpty()) {
            CustomerGroupInfo group = customerGroupMapper.findByGroupIdAndType(customerFileShare.getGroupCode(), 2);
            if (group != null) {
                groupMap = new HashMap<>();
                groupMap.put(group.getGroupId(), group);
            }
        }

        // 查询文件信息
        Map<String, CustomerFile> fileMap = null;
        if (customerFileShare.getFileKey() != null && !customerFileShare.getFileKey().trim().isEmpty()) {
            CustomerFile customerFile = customerFileMapper.findByFileKey(customerFileShare.getFileKey());
            if (customerFile != null) {
                fileMap = new HashMap<>();
                fileMap.put(customerFile.getFileKey(), customerFile);
            }
        }

        FileShareInfoResp resp = FileShareRespHelper.convert2FileShareInfoResp(customerFileShare, groupMap, fileMap);
        return resp;
    }

    /**
     * 删除文件分享
     *
     * @param request 删除文件分享请求
     * @return 删除结果
     */
    public boolean deleteFileShare(DeleteFileShareRequest request) {
        // 查询分享记录是否存在
        Long recordId = Long.parseLong(request.getId());
        CustomerFileShare customerFileShare = customerFileShareMapper.selectById(recordId);
        if (customerFileShare == null) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR.getCode(), "分享记录不存在");
        }

        // 逻辑删除
        EntityUtil.logicalDelete(customerFileShare, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerFileShareMapper.updateById(customerFileShare);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }
        return true;
    }

    /**
     * 查询文件分享列表（分页）
     *
     * @param request 查询文件分享列表请求
     * @return 文件分享列表
     */
    public FileShareListResp queryFileShareList(QueryFileShareListRequest request) {
        // 创建分页对象
        Page<CustomerFileShare> page = new Page<>(request.getPageNum(), request.getPageSize());

        // 分页查询分享列表
        IPage<CustomerFileShare> sharePage = customerFileShareMapper.selectShareListPage(
                page,
                request.getShareId(),
                request.getFileKey(),
                request.getCustomerId(),
                request.getGroupCode(),
                request.getQrCodeOssKey(),
                request.getExpireAtStart(),
                request.getExpireAtEnd());

        // 批量查询分组信息
        Set<String> groupCodes = sharePage.getRecords().stream()
                .map(CustomerFileShare::getGroupCode)
                .filter(code -> code != null && !code.trim().isEmpty())
                .collect(Collectors.toSet());
        final Map<String, CustomerGroupInfo> groupMap;
        if (!groupCodes.isEmpty()) {
            List<CustomerGroupInfo> groups = customerGroupMapper.selectByType(2);
            groupMap = groups.stream()
                    .filter(g -> groupCodes.contains(g.getGroupId()))
                    .collect(Collectors.toMap(CustomerGroupInfo::getGroupId, g -> g));
        } else {
            groupMap = new HashMap<>();
        }

        // 批量查询文件信息
        Set<String> fileKeys = sharePage.getRecords().stream()
                .map(CustomerFileShare::getFileKey)
                .filter(key -> key != null && !key.trim().isEmpty())
                .collect(Collectors.toSet());
        final Map<String, CustomerFile> fileMap;
        if (!fileKeys.isEmpty()) {
            List<CustomerFile> files = customerFileMapper.selectByFileKeys(new ArrayList<>(fileKeys));
            fileMap = files.stream()
                    .collect(Collectors.toMap(CustomerFile::getFileKey, file -> file));
        } else {
            fileMap = new HashMap<>();
        }

        // 转换为响应对象
        List<FileShareInfoResp> fileList = sharePage.getRecords().stream()
                .map(share -> FileShareRespHelper.convert2FileShareInfoResp(share, groupMap, fileMap))
                .collect(Collectors.toList());

        FileShareListResp response = new FileShareListResp();
        response.setFileList(fileList);
        response.setTotal(sharePage.getTotal());
        response.setPageNum(request.getPageNum());
        response.setPageSize(request.getPageSize());
        response.setTotalPages((int) sharePage.getPages());

        return response;
    }
}

